<template>
    <div class="padding20">
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图-->
        <el-card>
            <!--添加角色按钮-->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe>
                <!--展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scoped" width="40px">
                        <el-row :class="['bdbottom',index1===0?'bdtop':'','vcenter']" v-for="(item1,index1) in scoped.row.children" :key="index1">
                            <!--一级权限-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRight(scoped.row,item1)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <!--二级权限-->
                                <el-row :class="[index2!=0?'bdtop':'','vcenter']" v-for="(item2,index2) in item1.children" :key="index2">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRight(scoped.row,item2)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!--三级权限遍历-->
                                        <el-tag type="warning" v-for="(item3,index3) in item2.children"
                                             :key="index3" closable @close="removeRight(scoped.row,item3)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!--索引列-->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scoped" width="40px">
                        <el-button type="primary"  size="mini" icon="el-icon-edit" @click="showEditDialog(scoped.row)">编辑</el-button>
                        <el-button type="warning"  size="mini" icon="el-icon-s-tools" @click="showSetRightDialog(scoped.row)">分配权限</el-button>
                        <el-button type="danger"  size="mini" icon="el-icon-delete" @click="delRole(scoped.row)" >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!--添加/修改 角色-->
        <el-dialog
            :title="isShowAddRoleDialog?`添加角色`:`编辑角色`"
            :visible.sync="showAddAndEditDialog"
            width="50%"
            @close="closeAddDialog">

            <!--内容主体区-->
            <el-form ref="roleFormRef" :model="addRoleFrom" :rules="addRoleFromRules" label-width="80px">
                <el-form-item label="角色名" prop="roleName" >
                    <el-input v-model="addRoleFrom.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleFrom.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            
            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeAddDialog">取 消</el-button>
                <el-button type="primary" @click="handleRoleDialogBtn">确 定</el-button>
            </span>
        </el-dialog>

        <!--设置权限Dialog-->
        <el-dialog
            title="分配权限"
            :visible.sync="isShowSetRightDialog"
            width="50%"
            @close="closeSetRightDialog">

            <!--内容主体区-->
            <el-tree
                ref="treeRef" 
                :data="rightsList"
                :props="treeProps" 
                show-checkbox 
                node-key="id"
                default-expand-all
                :default-checked-keys="defaultKeys"
            >
            </el-tree>

            <!--底部按钮区-->
            <span slot="footer">
                <el-button @click="closeSetRightDialog">取 消</el-button>
                <el-button type="primary" @click="handleSetRights">确 定</el-button>
            </span>
        </el-dialog>

        
    </div>
</template>

<script>
import {getRoles,removeRightById,setRoleRights,addRole,deleteRoleById,getRoleById,editRoleById} from '@/request/roles'
import {getRights} from '@/request/rights'
export default {
    props: {

    },
    components: {

    },
    data() {
        return {
            rolesList:[],
            isShowSetRightDialog:false,
            rightsList:null,
            treeProps:{   //树形控件绑定对象  --> 指定子集合+每一项名称
                label:'authName',
                children: 'children'
            },
            defaultKeys:[],  // 树形结构中默认选中的id节点 
            currentRole:null, //当前被打开dialog角色
            showAddAndEditDialog: false,
            isShowAddRoleDialog: false,  //判断是否点开的是添加角色按钮
            addRoleFrom:{
                roleName:``,
                roleDesc:``
            },
            addRoleFromRules:{
                roleName:[
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 2, max: 20, message: '描述在 5 到 20 个字符', trigger: 'blur' }
                ],
            }
        };
    },
    computed: {

    },
    created() {
        this.getRolesListData()
    },
    mounted() {

    },
    watch: {

    },
    methods: {
        showAddDialog(){
            this.showAddAndEditDialog =  true
            this.isShowAddRoleDialog = true
        },
        showEditDialog(roleInfo){
            
            getRoleById(roleInfo.id)
            .then(res=>{
                if(res.meta.status===200){
                   this.addRoleFrom = res.data
                   this.showAddAndEditDialog =  true
                   this.isShowAddRoleDialog = false
               }else{
                   this.$message.error('获取角色信息失败！')
               }
            })
        },
        closeAddDialog(){
            this.showAddAndEditDialog = false
            this.$refs.roleFormRef.resetFields()
            this.addRoleFrom = {
                roleName:``,
                roleDesc:``
            }
        },
        handleRoleDialogBtn(){
            this.isShowAddRoleDialog? this.handleAddRole() : this.handleEditRole()
        },
        handleAddRole(){
            this.$refs.roleFormRef.validate(async valid=>{
              if(valid){  //校验通过
                addRole(this.addRoleFrom)
                .then(res=>{
                    if(res.meta.status!=201){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.closeAddDialog()
                        this.getRolesListData()
                        this.$message.success('添加角色成功！')
                    }
                })
                .catch(err=>{
                    this.$message.error(err)
                })

              }else{
                  this.$message.error('请完善角色信息！')
              }
            })
        },
        handleEditRole(){
            console.log(this.addRoleFrom)
            this.$refs.roleFormRef.validate(async valid=>{
              if(valid){  //校验通过
                editRoleById(this.addRoleFrom.roleId,this.addRoleFrom)
                .then(res=>{
                    if(res.meta.status!=200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.closeAddDialog()
                        this.getRolesListData()
                        this.$message.success('修改角色信息成功！')
                    }
                })

              }else{
                  this.$message.error('请完善角色信息！')
              }
            })
        },
        async delRole(roleInfo){
            let delResult = await this.$confirm(`确定删除《${roleInfo.roleName}》角色吗?`,'提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .catch(err=>err)
            // 取消是cancel  确定是confirm
            if(delResult==='confirm'){
                deleteRoleById(roleInfo.id)
                .then(res=>{
                    if(res.meta.status!==200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.$message.success(res.meta.msg)
                        this.getRolesListData()  //刷新数据
                    }
                })
            }
        },
        async getRolesListData(){
            let res = await getRoles()
            if(res.meta.status!=200){
                return this.$message.error('获取角色列表数据失败')
            }else{
                this.rolesList = res.data
            }
        },
        async removeRight(role,tag){
            let delResult = await this.$confirm(`确定移除《${tag.authName}》权限吗?`,'提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .catch(err=>err)
            //取消是cancel  确定是confirm
            if(delResult==='confirm'){
                removeRightById(role.id,tag.id)
                .then(res=>{
                    if(res.meta.status!==200){
                        this.$message.error(res.meta.msg)
                    }else{
                        this.$message.success(res.meta.msg)
                        role.children = res.data  //移除后接口会返回该角色
                    }
                })
            }
        },
        async showSetRightDialog(role){
            this.currentRole = role
            //1.先获取全部权限信息
            let res = await getRights('tree')
            if(res.meta.status!==200){
                this.$message.error(res.meta.msg)
            }else{
                this.rightsList = res.data
                //2.弹窗打开
                this.isShowSetRightDialog = true
                //3.递归获取
                this.getLeaveKeys(role,this.defaultKeys)
            }
        },
        //通过递归获取角色下所有三级权限id，并绑到数组
        getLeaveKeys(node,arr){
            //如果没有children就是三级节点  直接拿到
            if(!node.children){
                return arr.push(node.id)
            }

            node.children.forEach(item => {
                this.getLeaveKeys(item,arr)
            });
        },
        closeSetRightDialog(){
            this.isShowSetRightDialog = false
            this.defaultKeys = []
        },
        handleSetRights(){
            //收集全部被选节点的key
            let keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            let idStr = keys.join(',')
            setRoleRights(this.currentRole.id,{ rids:idStr })
            .then(res=>{
                if(res.meta.status!==200){
                    this.$message.error(res.meta.msg)
                }else{
                    this.$message.success(res.meta.msg)
                    this.getRolesListData()  //刷新列表
                    this.defaultKeys = []
                    this.isShowSetRightDialog = false
                }
            })
        }
    }
    
};
</script>

<style scoped lang="less">
.el-card{
    width: 1200px;
}
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>
